<template>
  <view>
    <u-navbar
        title="预约沟通"
        @rightClick="rightClick"
        :autoBack="false"
    >
      <view slot="left"></view>
    </u-navbar>
    <view style="height: 100rpx"></view>
    <u-swiper
        height="400"
        circular
        :list="list"
        @change="swiperChange"
        @click="swiperClick"
    >
      <view
          slot="indicator"
          class="indicator-num"
      >
        <text class="indicator-num__text">{{ currentNum + 1 }}/{{ list.length }}</text>
      </view>
    </u-swiper>
    <view style="width: 700rpx;margin: 20rpx auto">
      <view style="float: right;margin-top: 20rpx" @click="clickWX">
        <u-icon name="weixin-fill" color="#1bd66c" size="40"></u-icon>
      </view>
      <!--    富文本渲染-->
      <rich-text :nodes="richTextHandle(productData.rich_text_content)"></rich-text>
      <p style="font-size: 36rpx;margin: 20rpx  0 10rpx;color: #4a5dff">开通个人会员，开始预约您的咨询时间</p>
      <view style="width: 100%;box-sizing: border-box;padding: 10rpx">
        <p style="display: flex">
          <u-icon size="20" name="clock"></u-icon>
          <span style="margin-left: 10rpx">选择时间</span>
        </p>

        <scroll-view @scroll="scroll" :scroll-left="scrollLeft" scroll-x="true" show-scrollbar="true"
                     style="width: 100%;white-space: nowrap;">
          <view :class="['tab',form.appointment_date===item.date?'active':'']" v-for="(item,index) in dateArr"
                :key="item.date"
                @click="tabChange(item.date,index)">
            <text>{{ item.week }}</text>
            <text>{{ item.date }}</text>
          </view>

        </scroll-view>

        <view style="width: 100%;display: flex;flex-wrap: wrap">
          <view :class="['time_slot',form.time_slot===item.value?'active':'']" v-for="(item,index) in timeSlotList"
                :key="item.date"
                @click="timeSlotChange(index)">
            <text>{{ item.value }}</text>
            <!--            约满-->
            <text :style="{color: item.count>10?'#4b4b4b':'#4a5dff'}">剩余：{{ 10 - item.count }}</text>
          </view>

        </view>


      </view>


    </view>

    <view style="height: 100rpx"></view>
    <view style="width: 700rpx;margin: 0 auto;position: fixed;bottom: 20rpx;left: 25rpx;background-color: #fff">
      <u-button
          :disabled="disabledGoAppointment"
          type="primary"
          style="bottom:30rpx;position: fixed;width: 600rpx;left: 75rpx"
          @click="goAppointment">立即预约
      </u-button>

    </view>

    <!--    右上角点击联系的弹窗-->
    <u-popup :show="showPhone" @close="showPhone = false" @open="showPhone = true" round="10" closeable mode="center">
      <view
          style="padding: 40rpx 80rpx; display: flex;justify-content: center;align-items: center;flex-direction: column">
        <u-image radius="5" :src="productData.qr_code" width="200" height="200"
                 @click="previewImage(productData.qr_code)"></u-image>
        <view style="color: #d5d5d5">点击扫码</view>
        <!--        <view style="font-size: 36rpx;display: flex;margin: 20rpx 0;align-items: center;justify-content: center">-->
        <!--          <u-icon name="phone" color="#4a5dff" size="24"></u-icon>-->

        <!--          <view style="margin-left: 10rpx" @click="call(productData.phone_number)">联系电话 :-->

        <!--            <text style="color: #4a5dff;text-decoration: underline">{{ productData.phone_number }}</text>-->
        <!--          </view>-->

        <!--        </view>-->
        <view style="font-size: 36rpx;display: flex;margin: 20rpx 0;align-items: center;justify-content: center;height: 50rpx;line-height: 50rpx">
          <u-icon name="clock" color="#4a5dff" size="20"></u-icon>
          <text style="margin-left: 10rpx">营业时间:{{ productData.business_hours }}</text>
        </view>


      </view>
    </u-popup>

    <u-popup :show="showForm" @close="showForm = false" @open="showForm = true" round="10" closeable>
      <view style="box-sizing: border-box;padding: 20rpx">
        <!--        商品详情模块-->
        <view>
          <view style="display: flex;padding-bottom: 16rpx">
            <!--            {{baseURL + currentProduct.image}}-->
            <u-image :src="currentProduct.image" width="80px" height="80px" @click="previewImage(currentProduct.image)"
                     radius="5"></u-image>

            <rich-text style="margin-left: 20rpx" :nodes="richTextHandle(currentProduct.rich_text_content)"></rich-text>

          </view>


        </view>
        <!--        表单填写模块-->
        <!--            @submit="onSubmit"-->
        <scroll-view style="height: 900rpx;" scroll-y="true">
          <view style="margin-top: 20rpx;overflow:hidden;">
            <view @click="form.category_id = item.id" :class="['category',item.id===form.category_id?'active':'' ]"
                  v-for="item in productData.category">
              <text>{{ item.title }}</text>
              <text>{{ item.price }}</text>
            </view>
          </view>
          <u-form
              labelPosition="top"
              labelWidth="auto"
              :model="form"
              :rules="rules"
              ref="uForm"
              v-if="productData.consultation_category"
          >
            <u-form-item label="您的咨询需求（多选）" prop="consultation_category" required>
              <!--              <u-input v-model="form.consultation_category" placeholder="请输入咨询类别"></u-input>-->
              <u-checkbox-group
                  placement="column"
                  v-model="form.consultation_category"
              >
                <u-checkbox
                    :customStyle="{marginLeft: '20rpx',marginBottom:'16rpx'}"
                    v-for="(item,index) in productData.consultation_category.split(';')"
                    :key="index"
                    :label="item"
                    :name="item"
                >
                </u-checkbox>
              </u-checkbox-group>
            </u-form-item>
            <u-form-item label="是否关注了小红书频道和微信视频号（单选）" prop="job_position" required>
              <!--              <u-input v-model="form.job_position" placeholder="请输入职位"></u-input>-->
              <u-radio-group
                  v-model="form.job_position"
                  v-if="productData.job_position"
              >
                <u-radio
                    :customStyle="{marginLeft: '20rpx'}"
                    v-for="(item,index) in productData.job_position.split(';')"
                    :key="index"
                    :label="item"
                    :name="item"
                >
                </u-radio>
              </u-radio-group>
            </u-form-item>
            <u-form-item required label="您在公司的职务" prop="responsibilities">
              <!--              <u-input v-model="form.responsibilities" placeholder="请输入职责"></u-input>-->
              <u-radio-group
                  v-model="form.responsibilities"
                  v-if="productData.responsibilities"
              >
                <u-radio
                    :customStyle="{marginLeft: '20rpx'}"
                    v-for="(item,index) in productData.responsibilities.split(';')"
                    :key="index"
                    :label="item"
                    :name="item"
                >
                </u-radio>
              </u-radio-group>
            </u-form-item>
            <!--            <u-form-item required label="贵司所属的企业类型是(单选)" prop="company_type">-->
            <!--              &lt;!&ndash;              <u-input v-model="form.company_type" placeholder="请输入公司类型"></u-input>&ndash;&gt;-->
            <!--              <u-radio-group-->
            <!--                  v-model="form.company_type"-->
            <!--                  v-if="productData.company_type"-->
            <!--              >-->
            <!--                <u-radio-->
            <!--                    :customStyle="{marginLeft: '20rpx'}"-->
            <!--                    v-for="(item,index) in productData.company_type.split(';')"-->
            <!--                    :key="index"-->
            <!--                    :label="item"-->
            <!--                    :name="item"-->
            <!--                >-->
            <!--                </u-radio>-->
            <!--              </u-radio-group>-->
            <!--            </u-form-item>-->

            <u-form-item required label="手机号" prop="phone_number">
              <u-input v-model="form.phone_number" placeholder="请输入手机号">
                <template slot="suffix">
                  <u-button
                      open-type="getPhoneNumber"
                      @getphonenumber="getUserPhone"
                      text="获取手机号"
                      type="primary"
                      size="mini"
                  ></u-button>
                </template>
              </u-input>
            </u-form-item>
            <u-form-item required label="正确填写要开的公司税号（客服Askmrmmm86)" prop="tax_number">
              <u-input v-model="form.tax_number" placeholder="请输入税号"></u-input>
            </u-form-item>
            <u-form-item required label="填写公司全名（和营业执照一致）" prop="company_name">
              <u-input v-model="form.company_name" placeholder="请输入公司名称"></u-input>
            </u-form-item>
            <u-form-item label="地址" prop="addressBefore" @click="addressPopup = true;">
              <u-input v-model="address" disabled disabledColor="#ffffff" border="none"
                        placeholder='选择地址'></u-input>
              <u-icon
                  slot="right"
                  name="arrow-right"
              ></u-icon>
            </u-form-item>
            <u-form-item required label="详细地址" prop="address">
              <view style="display: flex;align-items: center">
                <view style="flex: 6">
                  <u-textarea v-model="form.address" placeholder="请输入地址"></u-textarea>
                </view>
                <!--                <view style="flex: 1;display: flex;justify-content: center">-->
                <!--                  <u-icon @click="getMap" name="map" color="#4a5dff" size="28"></u-icon>-->
                <!--                </view>-->
              </view>
            </u-form-item>
          </u-form>
        </scroll-view>

      </view>
      <view style="width: 700rpx;margin: 0 auto">

        <u-button :disabled="disabledSubmitForm" type="primary" @click="submitForm" style="width: 600rpx">提交
        </u-button>
      </view>
      <view style="height: 20rpx"></view>


    </u-popup>
    <address-picker :show="addressPopup" closeOnClickOverlay @confirm='confirmAddress' @cancel='addressPopup=false'
                    @close='addressPopup = false' :address-data="addressData" :indexs="indexs" :areaId="areaId" :type="type"></address-picker>
  </view>
</template>

<script>

import {getAppointmentInfo, getDetailsByDay, getWxPhoneNumber, submitAppointment} from "@/api/request";
import {$http} from "@/utils/request";
export default {
  data() {
    return {
      // addressPopup: false,
      address: '',
      addressPopup: false,
      indexs: [0, 0, 0],
      areaId: [1, 110000, 110101],
      addressData: ['北京市', '北京市', '东城区'],
      type: 3, //1-省，2-省市，3-省市区
      showPhone: false,
      showForm: false,
      list: [
        'https://cdn.uviewui.com/uview/swiper/swiper1.png',
        'https://cdn.uviewui.com/uview/swiper/swiper2.png',
        'https://cdn.uviewui.com/uview/swiper/swiper3.png',
      ],

      rules: {
        consultation_category: [
          {type: 'array', required: true, message: '请选择咨询类别', trigger: 'blur'},
        ],
        job_position: [
          {required: true, message: '请选择职位', trigger: 'blur'},
        ],
        responsibilities: [
          {required: true, message: '请选择职责', trigger: 'blur'},
        ],
        company_type: [
          {required: true, message: '请选择公司类型', trigger: 'blur'},
        ],
        phone_number: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
        ],
        tax_number: [
          {required: true, message: '请输入税号', trigger: 'blur'},
        ],
        company_name: [
          {required: true, message: '请输入公司名称', trigger: 'blur'},
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'},
        ],
      },

      currentNum: 1,
      productData: {},
      baseURL: $http.baseUrl,
      dateArr: [],
      // active: '',
      scrollLeft: 0,
      //   true,appointment_date,2024-09-01,string,true,预约日期
      //   true,time_slot,,string,true,时间段
      // true,phone_number,,string,true,手机号
      // true,tax_number,,string,true,税号
      // true,company_name,,string,true,公司名称
      // true,category_id,1,string,true,
      //     true,consultation_category,,string,true,咨询类别
      // true,job_position,,string,true,职位
      // true,responsibilities,,string,true,职责
      // true,company_type,,string,true,公司类型
      form: {
        appointment_date: '',
        time_slot: '',
        phone_number: '',
        tax_number: '',
        company_name: '',
        category_id: '',
        consultation_category: [],
        job_position: '',
        responsibilities: '',
        company_type: '',
        address: '',
        addressBefore:''
      },
      timeSlotList: []


    };
  },
  methods: {
    //富文本处理 line-height: 1.5; 替换为 display: flex;align-items: center;
    richTextHandle(content) {
      console.log(content, 'content')
      if (!content) {
        return ''
      }
      return content.replace(/line-height/g, 'display: flex;align-items: center;padding-bottom: 200rpx;line-height')
    },


    confirmAddress(val) {
      console.log(val);
      this.address = val.value.join('')
      this.addressPopup = false
    },
    addressConfirm(data) {
      console.log(data, 'data')
      this.addressPopup = true
    },
    clickWX() {
      this.showPhone = true
    },

    rightClick() {
      console.log('rightClick')
    },
    swiperChange(e) {
      this.currentNum = e.current
      console.log('change', e)
    },
    swiperClick(e) {
      console.log('click', e)
      const urls = this.list.map(item => {
        return {src: item}
      })
      console.log(e, urls)
      // const data = this.list[e]
      this.previewImageList(e, this.list)
    },
    //getAppointmentInfo
    getAppointmentInfo() {
      getAppointmentInfo().then(res => {
        console.log(res, 'res')
        const data = res.data
        this.list = data.slideshow_image.split(';')
        this.productData = data
        this.form.category_id = data.category[0].id


        // this.list = res.data

      })
    },
    generateDate() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const week = date.getDay()
      const days = new Date(year, month, 0).getDate()
      const weekArr = ['日', '一', '二', '三', '四', '五', '六']
      const dateArr = []
      for (let i = 0; i < days; i++) {
        const weekIndex = (week + i) % 7
        dateArr.push({
          date: `${month}/${day + i}`,
          week: `星期${weekArr[weekIndex]}`,
          //年月日
          fullDate: `${year}-${this.addZero(month)}-${this.addZero(day + i)}`
        })
      }
      this.dateArr = dateArr
      this.form.appointment_date = dateArr[0].date
      console.log(dateArr, 'dateArr')
    },
    //补0
    addZero(num) {
      return num < 10 ? '0' + num : num
    },

    tabChange(date, index) {
      // console.log(e, 'e')
      console.log(index)
      this.form.appointment_date = date
      this.getDetailsByDay()
      // this.scrollLeft = index * (140+20)

    },
    scroll(e) {
      console.log(e, 'e')
      this.scrollLeft = e.detail.scrollLeft
    },
    submitForm() {
      this.$refs.uForm.validate().then(res => {
        // uni.$u.toast('校验通过')
        console.log(res, 'res')

        // 7/5 转为年月日
        const fullDate = this.dateArr.find(item => item.date === this.form.appointment_date).fullDate


        const params = {
          ...this.form,
          consultation_category: this.form.consultation_category.join(';'),
          appointment_date: fullDate,
          address: this.address+this.form.address
        }

        submitAppointment(params).then(res => {
          console.log(res, 'res')
          this.showForm = false
          //清空表单
          this.form = {
            appointment_date: '',
            time_slot: '',
            phone_number: '',
            tax_number: '',
            company_name: '',
            category_id: '',
            consultation_category: [],
            job_position: '',
            responsibilities: '',
            company_type: '',
            address: '',
          }
          const that = this
          setTimeout(() => {
            that.getDetailsByDay()
          }, 1500)


        })
      }).catch(errors => {
        // uni.$u.toast('校验失败')
        console.log(errors, 'errors')
      })
    },
    call(phone) {
      uni.makePhoneCall({
        phoneNumber: phone
      });
    },
    //查看图片详情
    previewImage(url) {
      uni.previewImage({
        current: url,
        urls: [url],
        //层级
        zIndex: 99999999
      });
    },
    //查看图片详情
    previewImageList(index, urls) {
      uni.previewImage({
        current: index,
        urls: urls,
        //层级
        zIndex: 99999999
      });
    },
    getDetailsByDay() {
      console.log('getDetailsByDay')
      const fullDate = this.dateArr.find(item => item.date === this.form.appointment_date).fullDate
      getDetailsByDay(fullDate).then(res => {
        console.log(res, 'res')
        this.timeSlotList = res.data
      })
    },
    timeSlotChange(index) {
      //判断count是否大于10
      if (this.timeSlotList[index].count > 10) {
        return
      }

      this.form.time_slot = this.timeSlotList[index].value
    },
    goAppointment() {
      if (this.productData.phone_number == '693226428'){
        uni.showToast({
          title: '预约成功',
          icon: 'none',
        });
        return

      }

      this.showForm = true
      //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
      this.$refs.uForm.setRules(this.rules)

    },
    getMap() {
      uni.chooseLocation({
        success: (res) => {
          console.log(res, 'res')
          this.form.address = res.address
        }
      });
    },
    getUserPhone(e) {
      // const _this = this
      // 获取到回调信息，需要code(与登录login的code不同)
      console.log("回调返回的信息：", e, e.detail.code)
      getWxPhoneNumber({
        code: e.detail.code
      }).then(res => {
        console.log(res, 'res')
        this.form.phone_number = res.data.phone_info.phoneNumber
      })
    },
  },
  onLoad() {
    this.getAppointmentInfo()
    //生成进一个月数据 日期和星期
    this.generateDate()
    this.getDetailsByDay()
    console.log(this.$refs, ' this.$refs')
  },
  computed: {
    //当前选中的商品
    currentProduct() {
      if (!this.productData.category) {
        return {}
      }

      return this.productData.category.find(item => item.id === this.form.category_id)
    },
    disabledGoAppointment() {
      return !(this.form.appointment_date && this.form.time_slot)
    },
    disabledSubmitForm() {
      return !(this.form.consultation_category.length && this.form.job_position && this.form.responsibilities  && this.form.phone_number && this.form.tax_number && this.form.company_name && this.form.address&& this.address)
    },


  },

};
</script>

<style scoped lang="scss">
//.indicator {
//@include flex(row);
//  justify-content: center;
//
//  &__dot {
//    height: 6px;
//    width: 6px;
//    border-radius: 100px;
//    background-color: rgba(255, 255, 255, 0.35);
//    margin: 0 5px;
//    transition: background-color 0.3s;
//
//    &--active {
//      background-color: #ffffff;
//    }
//  }
//}
.indicator-num {
  padding: 2px 0;
  background-color: rgba(0, 0, 0, 0.35);
  border-radius: 100px;
  width: 35px;
  @include flex;
  justify-content: center;

  &__text {
    color: #FFFFFF;
    font-size: 12px;
  }
}

.tab {
  padding: 10rpx 0;
  width: 140rpx;
  border-radius: 10rpx;
  border: #d5d5d5 1px solid;
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s;
  margin-left: 20rpx;
  margin-top: 10rpx;
  //active
  &.active {
    border-color: #4a5dff;
    font-weight: bold;
    background-color: #dde7f8;
  }

  //&:first-child {
  //  color: #d5d5d5
  //}
}

.time_slot {
  padding: 10rpx 0;
  width: 200rpx;
  border-radius: 10rpx;
  border: #d5d5d5 1px solid;
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s;
  margin-left: 20rpx;
  margin-top: 30rpx;

  text:nth-child(1) {
    font-size: 24rpx;
  }

  text:nth-child(2) {
    color: #4a5dff;
    font-size: 24rpx;
    margin-top: 10rpx;

  }

  //active
  &.active {
    border-color: #4a5dff;
    font-weight: bold;
    background-color: #dde7f8;
  }

  //&:first-child {
  //  color: #d5d5d5
  //}
}

.category {
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 10rpx 14rpx;
  border: 1px solid #d5d5d5;
  border-radius: 6rpx;
  margin-top: 30rpx;
  transition: all 0.3s;

  &.active {
    border-color: #4a5dff;
    font-weight: bold;
    background-color: #dde7f8;
  }

}
///deep/ .rich-txt-p {
//  font-size: 36rpx !important;
//  line-height: 100rpx !important;
//  color: #4b4b4b !important;
//}
</style>
